package org.grow.safety.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.grow.authfilter.entity.UserInfo;
import org.grow.authfilter.entity.UserLoginDto;
import org.grow.safety.dao.UserInfoDao;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @Author: xwg
 * @CreateDate: 21-8-4
 */
@Slf4j
@Service
public class AfterAuthSuccess implements AuthenticationSuccessHandler {
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        UserInfo principal = (UserInfo) authentication.getPrincipal();

        response.setStatus(200);
        UserLoginDto userLoginDto = new UserLoginDto();

        BeanUtils.copyProperties(principal,userLoginDto);
//        Map<String,Object>  dto
//        开发坐火箭 维护火葬场
        String s = objectMapper.writeValueAsString(userLoginDto);


        response.getWriter().println(s);
        System.out.println("==============>>>>>>>>>>成功替换conditionalBean");
        principal.setLastLoginTime(LocalDateTime.now());
//   如何进行jpa继承     userInfoDao.save(principal);
//


        log.info("用户"+principal.getUsername()+"登录系统");
    }
}
